/*
 * @Author: chunlai
 * @Date: 2023-07-25 09:48:14
 * @LastEditTime: 2025-09-01 15:13:40
 * @LastEditors: minsheng_insurance_agency_zhoucl
 * @FilePath: \02.bldinsure\src\translate\risks\rules.js
 * @Description:险种投保规则配置
 */
import { userAge } from "@/methods/globals.js";
import { fmtWanYuan } from "@/methods/format.js";
import { Toast } from "vant";
import store from "@/store/index";

export const validRules = (list, data, rootState, type) => {
  // console.log("validRules");
  let insertParams = store.state.insert;
  const applicant = insertParams.applicant;
  const bbrArr = insertParams.bbrMultList,
    bbr0Item = bbrArr[0],
    bbrNum = bbrArr.length;
  let state = [];
  let re_count_flag = "0"; // 二次试算标识(11)
  let mainRisk = list.find((todo) => todo.ismain),
    mainAmnt = mainRisk?.amnt ?? 0, // 防止 mainRisk 为 undefined
    mainPrem = (mainRisk?.prem ?? 0) * 1,
    insuAge = userAge(bbr0Item?.birthDate),
    insuSex = bbr0Item?.sex ?? "0",
    insuRela = `${bbr0Item?.relationToAppnt ?? ""}`,
    appntOccu = applicant?.occupationClass ?? "",
    insuOccu = bbr0Item?.occupationClass ?? "",
    insuOccuName = bbr0Item?.occupationCodeName ?? "",
    insuSheBao = bbr0Item?.socialInsuFlag ?? "",
    appntAge = applicant?.birthDate
      ? userAge(applicant.birthDate)
      : applicant?.age ?? 0;
  const isYuluFlag = rootState.page.isPrerecordOrder;
  // 多被保人年龄取最大值
  if (bbrNum > 1) {
    insuAge = Math.max(...bbrArr.map((e) => userAge(e?.birthDate)));
  }
  // console.log("validRules--", insuAge);
  const newState = JSON.parse(JSON.stringify(list));
  /* ======= 已选信息赋值 =======*/
  state = newState
    .map((item, index) => {
      /* ===== 字段修改/赋值 ===== */
      if (item.varietyCode == data.varietyCode) {
        item[data.type] = data.val;
        if (data.valTypeKey) {
          item[data.valTypeKey] = data.valType;
        }
        if (data.type == "planCode") {
          if (item.planSubName !== void 0) {
            const plan0Tag = item.plansList.find(
              (p0) => p0.value == item.planCode
            );
            if (plan0Tag) {
              item.planSubName = plan0Tag.subName;
            }
          }
        }
      }

      /* ===== 选项设置/过滤 ===== */
      /* === 投保份数 === */
      // 0.缴费年期校验份数最大值 -new
      if (item.payYearCheckMultMax && item.payYearCheckMultMax.length > 0) {
        let mult2Tag = item.payYearCheckMultMax.find((ele9) =>
          ele9.value.includes(`${item.payendyear}`)
        );
        if (mult2Tag) {
          item.multMax = mult2Tag.max;
          if (item.mult > item.multMax) {
            item.mult = item.multMax;
          }
        }
      }
      // 1.计算保费-new
      if (item.multCountPrem) {
        item.prem = item.mult * item.countBaseMoney;
      }
      if (item.fixPremType && item.fixPremType == "bbNumber") {
        item.prem = `${bbrNum * Number(item.basePrem)}`;
      }
      // 2.计算保额-new
      if (item.multCountAmnt) {
        item.amnt = item.mult * item.countBaseMoney;
      }
      // 3.份数选择 -new
      if (item.multArr && item.multArr.length > 0) {
        item.multList = item.multArr.filter((multNum) => {
          let flag = true;
          if (multNum.maxAge && multNum.maxAge < insuAge) {
            flag = false;
          }
          return flag;
        });
        let multTag = findListObj(item.multList, item.mult);
        if (!multTag) {
          multTag = item.multList[0] || {};
          item.mult = multTag.value;
        }
      }
      // 4.泰康
      if (item.amntPremSet) {
        if (item.amntPremSet == "amntArr") {
          const filt2Arr = item.firstInsureConfigs.filter((item) => {
            return insuAge >= item.minAge && insuAge <= item.maxAge;
          });
          if (filt2Arr && filt2Arr.length > 0) {
            const filterObj = filt2Arr[0];
            item.programmeName = filterObj.insurType || "";
            // 泰康职业4类保额降低
            let caseArr = insuOccu == "4" ? filterObj.cases_2 : filterObj.cases;
            item.amntArr = caseArr;
          }
        }
      }
      // 5.预录单保费设置-new(长城/10303)
      if (isYuluFlag && item.preOrderPrem) {
        item.prem = item.preOrderPrem;
      }
      /* === 险种计划类 === */
      // 1.计划所属大类(为了给plans赋值,该参数值不参与保费的试算)-new
      if (item.planBiggerArr && item.planBiggerArr.length > 0) {
        item.planBiggerList = item.planBiggerArr.filter((planI) => {
          let flag = true;
          return flag;
        });
        let planBiggerTag = findListObj(item.planBiggerList, item.planBig);
        if (!planBiggerTag) {
          planBiggerTag = item.planBiggerList[0];
          item.planBig = planBiggerTag.value;
        }
        /*初始化 + 点击大类按钮 >>> 赋值*/
        if (item.plansArr.length === 0 || data.type === "planBig") {
          // 1-1.计划大类所属的 小类
          if (planBiggerTag.plansArr) {
            item.plansArr = planBiggerTag.plansArr;
          }
          // 1-2.计划大类所属的 责任
          if (planBiggerTag.dutyArr) {
            item.dutyList = planBiggerTag.dutyArr;
          }
          if (planBiggerTag.deductiblesList) {
            item.deductiblesList = planBiggerTag.deductiblesList;
          }
        }
      }
      // 2.计划选择(含编码)-new
      if (item.plansArr && item.plansArr.length > 0) {
        item.plansList = item.plansArr.filter((planI) => {
          let flag = true;
          if (planI.maxAge && insuAge > planI.maxAge) {
            flag = false;
          }
          // INIT_PLANSS中初始化过滤迁至此处
          if (planI.hasSocial && planI.hasSocial !== insuSheBao) {
            flag = false;
          }
          if (planI.bbrNum && planI.bbrNum != bbrNum) {
            flag = false;
          }
          return flag;
        });
        let planTag = findListObj(item.plansList, item.planCode);
        if (!planTag) {
          /**计划名替换*/
          if (item.planSubName) {
            planTag = item.plansList.find(
              (c2) => c2.subName == item.planSubName
            );
          }
          if (!planTag) {
            planTag = item.plansList[0];
          }
          item.planCode = planTag.value;
          if (item.planSubName) {
            item.planSubName = planTag.subName;
          }
        }
        // 2-1.计划对应的保障责任列表
        if (planTag.guarantees) {
          item.guaranteesList = planTag.guarantees;
        }
        // 2-2.产品计划固定保额/保费(华安、平安、众惠)
        if (planTag.fixAmnt) {
          item.amnt = planTag.fixAmnt;
          item.amntType = "text";
        }
        if (planTag.fixPrem) {
          item.prem = planTag.fixPrem;
          item.premType = "text";
        }
        if (planTag.fixInsuYear) {
          item.insuYear = planTag.fixInsuYear;
        }
        if (planTag.fixInsuYearType) {
          item.insuYearType = planTag.fixInsuYearType;
        }
        // 选计划1不能加附加被保人
        if (
          ["110176", "110194"].includes(item.varietyCode) &&
          item.planCode === "1" &&
          bbrNum > 1
        ) {
          item.planCode = item.plansList[1].value;
        }
      }
      /* === 养老年金 === */
      // 1.领取时间
      if (item.pullAgeArr && item.pullAgeArr.length > 0) {
        item.pullAgeList = item.pullAgeArr.filter((pullAge) => {
          let flag = true;
          if (pullAge.maxAge && pullAge.maxAge < insuAge) {
            flag = false;
          }
          if (pullAge.sexLimit && pullAge.sexLimit != insuSex) {
            flag = false;
          }
          return flag;
        });
        let pullAgeTag = findListObj(item.pullAgeList, item.pullAge);
        if (!pullAgeTag) {
          pullAgeTag = item.pullAgeList[0] || {};
          item.pullAge = pullAgeTag.value;
        }
        if (pullAgeTag.payendyearArr) {
          item.payendyearArr = pullAgeTag.payendyearArr;
        }
        // planCodePayYear(利安)
        if (pullAgeTag.planCodePayYear) {
          const fd1Plan = findListObj(
            pullAgeTag.planCodePayYear,
            item.planCode,
            "planCode"
          );
          if (fd1Plan) {
            if (fd1Plan.payendyearArr) {
              item.payendyearArr = fd1Plan.payendyearArr;
            }
          }
        }
      }
      // 2.领取频次
      if (item.pullMethodArr && item.pullMethodArr.length > 0) {
        let pullFrequencyTag = findListObj(item.pullMethodArr, item.pullMethod);
        if (!pullFrequencyTag) {
          pullFrequencyTag = item.pullMethodArr[0];
          item.pullMethod = pullFrequencyTag.value;
        }
      }
      if (item.pullMethodRela === "mainSame" && mainRisk.pullMethod) {
        item.pullMethod = mainRisk.pullMethod;
      }
      // 3.领取方式
      if (item.pullMoneyMethodList && item.pullMoneyMethodList.length > 0) {
        let pullMethodTag = findListObj(
          item.pullMoneyMethodList,
          item.planCode
        );
        if (!pullMethodTag) {
          pullMethodTag = item.pullMoneyMethodList[0];
          item.planCode = pullMethodTag.value;
        }
      }
      // 恒大LA078(待测试)
      if (item.pullAgeRela !== undefined) {
        const relaObj = item.pullAgeRela;
        // 1.年金领取年龄=保险期间-1
        if (relaObj.type === "insurSlice") {
          item.pullAge = Number(item.insuYear) - relaObj.value;
        }
      }

      /* === 保障期限 --- ok === */
      // 1.列表过滤/赋值
      if (item.insureYearArr && item.insureYearArr.length > 0) {
        item.insureYearList = item.insureYearArr.filter((insYear) => {
          let flag = true;
          if (insYear.maxAge && insYear.maxAge < insuAge) {
            flag = false;
          }
          // 长城(10210)附加险保险期间 < 主险(暂未用到的字段值)
          // if (item.insuYearRela == "lessMain" && insYear.value - 0 > mainRisk.insuYear) {
          // 	flag = false
          // }
          // 被保人性别差异限制年龄上限(合众)
          if (insYear.sexMaxAge !== undefined && insuSex == insYear.sexLimit) {
            flag = insYear.sexMaxAge >= insuAge;
          }
          // 附加两全险: 缴费期间+保障期间+被保人年龄  利安/412001
          if (item.insuYearRela == "limitByPayyearAge") {
            const findObj1 = insYear.payYearAgeLimit.find((ele3) =>
              ele3.payyear.includes(mainRisk.payendyear)
            );
            flag = findObj1 && insuAge <= findObj1.maxAge;
          }
          return flag;
        });
        let insuTag = findListObj(item.insureYearList, item.insuYear);
        if (!insuTag) {
          insuTag = item.insureYearList[0];
          item.insuYear = insuTag.value;
        }
        if (insuTag.type) {
          item.insuYearType = insuTag.type;
        }
        if (insuTag.setPullAge) {
          item.pullAge = insuTag.setPullAge;
        }
        // 如果保障期限下配置有缴费年期 即使用
        if (insuTag.payendyearArr) {
          item.payendyearArr = insuTag.payendyearArr;
        }
      }
      // 2.保险期间规则
      if (item.insurYearRela) {
        if (item.insurYearRela == "mainInsurSame") {
          // 保险期间=主险保险期间
          item.insuYear = mainRisk.insuYear;
          item.insuYearType = mainRisk.insuYearType;
        } else if (item.insurYearRela == "mainInsur2Same") {
          // 保险期间=主险保险期间;缴费期间列表=主险的
          item.insuYear = mainRisk.insuYear;
          item.insuYearType = mainRisk.insuYearType;
          item.payendyearArr = mainRisk.payendyearArr;
        } else if (item.insurYearRela == "mainPayendSame") {
          // 保险期间=主险交费期间
          if (mainRisk.payendyear !== "趸交") {
            item.insuYear = mainRisk.payendyear;
            item.insuYearType = mainRisk.payendyearType;
          }
        } else if (item.insurYearRela == "mainPayendSameSlice") {
          // 保险期间=主险交费期间
          if (mainRisk.payendyear !== "趸交") {
            item.insuYear = mainRisk.payendyear * 1 - 1;
            item.insuYearType = mainRisk.payendyearType;
          }
        }
      }

      /* === 缴费年期 --- ok === */
      // 1.列表过滤/赋值
      if (item.payendyearArr && item.payendyearArr.length > 0) {
        item.payendyearList = item.payendyearArr.filter((payYear) => {
          let flag = true;
          if (payYear.maxAge && payYear.maxAge < insuAge) {
            flag = false;
          }
          return flag;
        });
        let payEdnTag = findListObj(item.payendyearList, item.payendyear);
        if (!payEdnTag) {
          payEdnTag = item.payendyearList[0] || {};
          item.payendyear = payEdnTag.value;
        }
        if (payEdnTag.type) {
          item.payendyearType = payEdnTag.type;
        }
        // 如果缴费年期下配置有保障期限  即使用
        if (payEdnTag.insureYearArr) {
          item.insureYearArr = payEdnTag.insureYearArr;
        }
      }
      // 2.附加险缴费年期取主险赋值
      if (item.payendYearRela !== undefined) {
        const payendYearRelaMs = item.payendYearRela;
        if (
          payendYearRelaMs === "mainSlice" &&
          mainRisk.payendyear !== "趸交"
        ) {
          item.payendyear = mainRisk.payendyear - 1; //交费期间=主险交费期间-1;
        } else if (item.payendYearRela == "mainSame") {
          item.payendyear = mainRisk.payendyear;
          // 待确定
          if (item.payendyearList) {
            let tagyear = findListObj(item.payendyearList, item.payendyear);
            if (!tagyear) {
              item.errorTip = "当前主险缴费年期无法匹配该附加险";
              item.canChoose = true;
              item.checked = false;
              item.preChecked = true;
            } else {
              item.preChecked = false;
            }
          }
        }
        item.payendyearType = mainRisk.payendyearType;
      }
      // 保险期间=交费期间
      if (item.insurYearRela && item.insurYearRela == "sameItemPayYear") {
        item.insuYear = item.payendyear;
        item.insuYearType = item.payendyearType;
      }
      /* === 保额选择 -new === */
      if (item.amntArr && item.amntArr.length > 0) {
        let maxAmnt2 = 0;
        // 年龄校验过滤保额---104256
        if (item.ageIntervalLimitAmnt && item.ageIntervalLimitAmnt.length > 0) {
          const hz256v1 = item.ageIntervalLimitAmnt.find(
            (ele) => insuAge >= ele.minAge && insuAge <= ele.maxAge
          );
          if (hz256v1) {
            maxAmnt2 = Number(hz256v1.maxAmnt);
          }
        }
        item.amntList = item.amntArr.filter((amnI) => {
          let flag = true;
          if (amnI.maxAge && amnI.maxAge < insuAge) {
            flag = false;
          }
          if (amnI.minAge && amnI.minAge > insuAge) {
            flag = false;
          }
          if (maxAmnt2 !== 0 && Number(amnI.value) > maxAmnt2) {
            flag = false;
          }
          if (amnI.minMainPrem !== undefined) {
            if (re_count_flag === "0") {
              re_count_flag = "1";
            }
            if (amnI.minMainPrem >= mainPrem) {
              flag = false;
            }
          }
          // 缴费期间限制保额过滤条件---惠泽104296
          if (item.payYearFilteAnmtArr && item.payYearFilteAnmtArr === "1") {
            const obj4 = findListObj(item.payendyearList, item.payendyear);
            if (obj4) {
              if (obj4.minAmnt && Number(amnI.value) < obj4.minAmnt) {
                flag = false;
              }
              if (obj4.maxAmnt && Number(amnI.value) > obj4.maxAmnt) {
                flag = false;
              }
            }
          }
          return flag;
        });
        let amntTag = findListObj(item.amntList, item.amnt);
        if (!amntTag) {
          /* 二次试算: 已选险种 + 有需要的试算校验因子字段,即re_count_prem = 1 */
          if (item.checked && re_count_flag !== "11") {
            re_count_flag = `${re_count_flag}1`;
          }
          amntTag = item.amntList[0] || {};
        }
        item.amnt = amntTag.value || "0";
        if (amntTag.prem) {
          item.prem = amntTag.prem;
        }
        if (amntTag.insurInfo) {
          item.dutyAmntPremTable = amntTag.insurInfo;
        }
      }
      // 2-1.与主险基本保额固定比例为1:1-new
      if (item.amntRela == "mainSame") {
        item.amnt = mainRisk.amnt;
      }
      // 2-2.同主险保费(豁免险种 old: tbExempt)-new
      if (item.amntRela == "sameMainPrem") {
        item.amnt = mainPrem;
      }
      // 2-3.主险保费*剩余交费期间(百年5933)
      if (item.amntRela == "premXreyear" && mainRisk.payendyear != "趸交") {
        item.amnt = mainPrem * (mainRisk.payendyear - 1);
      }

      /* === 保障责任选择(多选)-new === */
      if (item.liabilityList && item.liabilityList.length > 0) {
        // 必选责任(长城)
        let mustDuty = findListObj(item.liabilityList, "must", "type");
        let mustAmnt = mainRisk.amnt;
        if (mustDuty) {
          mustAmnt = mustDuty.amnt;
        }
        item.liabilityList.forEach((dut) => {
          if (dut.amntType == "mustCalc") {
            dut.amnt = mainRisk.amnt / dut.rate;
          }
          if (dut.type && dut.type == "must") {
            item.amnt = dut.amnt;
          }
          if (dut.maxMainrate) {
            if (dut.amnt > mustAmnt * dut.maxMainrate) {
              Toast("保额不超过必选责任" + dut.maxMainrate + "倍");
              dut.amnt = mustAmnt * dut.maxMainrate;
            }
          }
        });
      }
      if (item.duty3List && item.duty3List.length > 0) {
        const dty3Len = item.duty3List.length;
        for (let a = 0; a < dty3Len; a++) {
          const dty3Item = item.duty3List[a];
          if (dty3Item.chooseLimit) {
            const dty3ChkObj = dty3Item.chooseLimit;
            if (dty3ChkObj.minAmnt && item.amnt < dty3ChkObj.minAmnt) {
              if (dty3Item.isChecked) {
                dty3Item.isChecked = false;
                dty3Item.value = "0";
                dty3Item.errTips = `基本保额${fmtWanYuan(
                  dty3ChkObj.minAmnt
                )}元(含)以上可选`;
              } else {
                dty3Item.errTips = "";
              }
            }
          }
        }
      }
      if (item.dutyList && item.dutyList.length > 0) {
        // console.log(appntOccu);
        if (mainRisk.varietyCode == "1926") {
          const fd2Dty = findListObj(item.dutyList, "3");
          if (fd2Dty && fd2Dty.isCheck) {
            if (insuRela == "4") {
              Toast(
                "选择“投保人意外身故或全残豁免保险费”责任，投被保人不能为同一人"
              );
              fd2Dty.isCheck = false;
            } else if (appntOccu >= 5) {
              Toast(
                "选择“投保人意外身故或全残豁免保险费”责任，投保人职业五级（含）以上职业不得投保本险"
              );
              fd2Dty.isCheck = false;
            }
          }
        }
        if (mainRisk.varietyCode == "5931") {
          const fd1Dty = findListObj(item.dutyList, "2");
          if (fd1Dty && !fd1Dty.isCheck) {
            item.dutyList[1].isCheck = false;
            item.dutyList[2].isCheck = false;
          }
        }
        if (mainRisk.varietyCode == "110161") {
          const fd3Dty = findListObj(item.dutyList, "疾病关爱保险金", "label");
          if (fd3Dty && fd3Dty.labelChange) {
            const fd31Dty = fd3Dty.labelChange.find(
              (d2) =>
                d2.insuYear.indexOf(`${item.insuYear}${item.insuYearType}`) !=
                -1
            );
            if (fd31Dty) {
              fd3Dty.label = fd31Dty.value;
            }
          }
        }
        // 新增公共规则
        if (item.dutyValideRules !== void 0) {
          const fd4Dty = findListObj(
            item.dutyList,
            item.dutyValideRules.dutyValue
          );
          if (fd4Dty && fd4Dty.isCheck) {
            if (item.dutyValideRules.disSelfRela && insuRela == "4") {
              Toast(`选择“${fd4Dty.label}”责任，投被保人不能为同一人`);
              fd4Dty.isCheck = false;
            } else if (
              item.dutyValideRules.tbrOccuMaxLevel !== void 0 &&
              appntOccu >= item.dutyValideRules.tbrOccuMaxLevel
            ) {
              Toast(
                `选择“${fd4Dty.label}”责任，投保人职业${item.dutyValideRules.tbrOccuMaxLevel}级（含）以上职业不得投保本险`
              );
              fd4Dty.isCheck = false;
            }
          }
        }
      }

      // 3.计划关联的住院免赔额(含编码)-new
      if (item.deductiblesList && item.deductiblesList.length > 0) {
        let deduTag = findListObj(item.deductiblesList, item.deductibleCode);
        if (!deduTag) {
          deduTag = item.deductiblesList[0];
          item.deductibleCode = deduTag.value;
        }
      }

      /* ======= rules规则外,初步校验(主险使用较多) ======= */
      const rulesList = item.rules || [];
      if (rulesList.length > 0) {
        const findPrem = findListObj(rulesList, "premLimit", "type"),
          findAnmt = findListObj(rulesList, "amntLimit", "type"),
          find1Obj = findListObj(item.payendyearArr, item.payendyear);
        if (find1Obj) {
          // 1.保费校验类-new
          if (findPrem && findPrem.check_payendyear === "1") {
            if (find1Obj.minPrem) {
              findPrem.minPrem = find1Obj.minPrem;
              if (Number(item.prem) < find1Obj.minPrem) {
                Toast(
                  `${item.productName}，交费期间选择${find1Obj.label}，最低保费为${find1Obj.minPrem}元`
                );
                item.prem = find1Obj.minPrem;
              }
            } else if (find1Obj.maxPrem) {
              findPrem.maxPrem = find1Obj.maxPrem;
              if (Number(item.prem) > find1Obj.maxPrem) {
                // 最高保费校验
                Toast(
                  `${item.productName}，交费期间选择${find1Obj.label}，最高保费为${find1Obj.maxPrem}元`
                );
                item.prem = find1Obj.maxPrem;
              }
            }
            //  else if (item.checkBaseMoney && Number(item.prem) % item.checkBaseMoney != 0) {
            // 	Toast(`保费须为 ${item.checkBaseMoney} 元的整数倍`);
            // 	item.prem = findObj4.minPrem || findObj4.maxPrem;
            // }
          }
          // 2.保额校验类-new
          if (findAnmt && findAnmt.check_payendyear === "1") {
            if (find1Obj.minAmnt) {
              findAnmt.minAmnt = find1Obj.minAmnt;
              if (Number(item.amnt) < find1Obj.minAmnt) {
                Toast(
                  `${item.productName}，交费期间选择${find1Obj.label}，最低保额为${find1Obj.minAmnt}元`
                );
                item.amnt = find1Obj.minAmnt;
              }
            } else if (find1Obj.maxAmnt) {
              findAnmt.maxAmnt = find1Obj.maxAmnt;
              if (Number(item.amnt) > find1Obj.maxAmnt) {
                Toast(
                  `${item.productName}，交费期间选择${find1Obj.label}，最高保额为${find1Obj.maxAmnt}元`
                );
                item.amnt = find1Obj.maxAmnt;
              }
            }
          }
        }
      }
      return item;
    })
    /* ======= 已选险种信息rules校验 =======*/
    .map((item, index, arr) => {
      /* === rules公共校验规则 === */
      if (item.rules && item.rules.length > 0) {
        const ruleLen = item.rules.length;
        if (!item.preChecked) {
          item.errorTip = "";
          item.canChoose = false;
        }
        for (let i = 0; i < ruleLen; i++) {
          let ele = item.rules[i];
          if (item.ismain || item.checked) {
            if (ele.type == "amntLimit") {
              // 保额校验限制
              if (ele.maxAmnt && Number(item.amnt) > ele.maxAmnt) {
                item.amnt = ele.maxAmnt;
                let errMsg = `${item.productName}，最高保额${ele.maxAmnt}元`;
                if (item.amntRela && item.amntRela == "sameMainPrem") {
                  errMsg += `，且保额需等同主险保费`;
                  item.canChoose = true;
                  item.checked = false;
                  item.errorTip = `最高保额${ele.maxAmnt}元，且保额需等同主险保费`;
                }
                Toast(`${errMsg}`);
                break;
              } else if (ele.minAmnt && Number(item.amnt) < ele.minAmnt) {
                item.amnt = ele.minAmnt;
                let err2Msg = `${item.productName}，最低保额${ele.minAmnt}元`;
                if (item.amntRela && item.amntRela == "sameMainPrem") {
                  err2Msg += `，且保额需等同主险保费`;
                  item.canChoose = true;
                  item.checked = false;
                  item.errorTip = `最低保额${ele.minAmnt}元，且保额需等同主险保费`;
                }
                Toast(`${err2Msg}`);
                break;
              } else if (
                ele.checkBaseMoney &&
                Number(item.amnt) % ele.checkBaseMoney !== 0
              ) {
                item.amnt = ele.minAmnt || ele.maxAmnt;
                Toast(
                  `${item.productName}，保额需为 ${ele.checkBaseMoney} 元的整数倍`
                );
                break;
              }
              if (
                ele.ageCheckAmnt !== undefined &&
                ele.ageCheckAmnt.length > 0
              ) {
                const ageObj = ele.ageCheckAmnt.find(
                  (it3) => insuAge >= it3.minAge && insuAge <= it3.maxAge
                );
                if (ageObj) {
                  if (
                    ageObj.minAmnt !== undefined &&
                    Number(item.amnt) < ageObj.minAmnt
                  ) {
                    Toast(
                      `${ageObj.minAge}-${ageObj.maxAge}周岁，投保本险种最低基本保额为${ageObj.minAmnt}元`
                    );
                    item.amnt = ageObj.minAmnt;
                    break;
                  } else if (
                    ageObj.maxAmnt !== undefined &&
                    Number(item.amnt) > ageObj.maxAmnt
                  ) {
                    Toast(
                      `${ageObj.minAge}-${ageObj.maxAge}周岁，投保本险种最高基本保额为${ageObj.maxAmnt}元`
                    );
                    item.amnt = ageObj.maxAmnt;
                    break;
                  } else if (
                    ageObj.baseLevel &&
                    Number(item.amnt) % ageObj.baseLevel != 0
                  ) {
                    Toast(`基本保额须为${ageObj.baseLevel}元整数倍`);
                    item.amnt = ageObj.minAmnt || ageObj.maxAmnt;
                    break;
                  }
                }
              }
              if (
                ele.occuLimitAmnt !== undefined &&
                ele.occuLimitAmnt.length > 0
              ) {
                const checkList4 = ele.occuLimitAmnt,
                  len4 = checkList4.length;
                for (let i = 0; i < len4; i++) {
                  const item4 = checkList4[i];
                  if (
                    insuOccuName === item4.code &&
                    Number(item.amnt) > item4.value
                  ) {
                    item.amnt = item4.value + "";
                    Toast(
                      `被保人所选职业为特殊职业，所选保额不得大于${
                        item4.value / 10000
                      }万，请重新选择保额`
                    );
                    break;
                  }
                }
              }
              if (ele.mainAmntMulMax !== undefined) {
                if (Number(item.amnt) > mainAmnt * ele.mainAmntMulMax) {
                  item.amnt = mainAmnt * ele.mainAmntMulMax;
                  Toast(
                    `${item.productName}，最高保额不超过主险保额的${ele.mainAmntMulMax}倍`
                  );
                  break;
                }
              }
              if (ele.amntRateToOtherRisk !== undefined) {
                /*与target险种保额的投保比例值*/
                let checkObj1 = {};
                if (Array.isArray(ele.amntRateToOtherRisk)) {
                  checkObj1 = ele.amntRateToOtherRisk.find((ele) => {
                    let flag = false;
                    arr.forEach((li) => {
                      if (ele.target.includes(li.varietyCode)) {
                        flag = true;
                      }
                    });
                    return flag;
                  });
                } else {
                  checkObj1 = ele.amntRateToOtherRisk;
                }
                const targetArr = Array.isArray(checkObj1.target)
                    ? checkObj1.target
                    : [checkObj1.target],
                  findItem1 = arr.find(
                    (insu) =>
                      targetArr.includes(insu.varietyCode) &&
                      (insu.checked || insu.ismain)
                  );
                if (findItem1) {
                  if (checkObj1.maxRate !== undefined) {
                    const maxRateVal = (findItem1.amnt - 0) * checkObj1.maxRate;
                    if (maxRateVal < Number(item.amnt)) {
                      item.amnt = ele.minAmnt || ele.maxAmnt;
                      let resValue = `${checkObj1.maxRate}倍`;
                      if (checkObj1.maxRate < 1) {
                        resValue = `${checkObj1.maxRate * 100}%`;
                      }
                      Toast(
                        `${item.productName}，最高保额不能超过 ${findItem1.productName} 保额的 ${resValue} `
                      );
                    }
                  } else if (checkObj1.minRate !== undefined) {
                    const minRateVal = (findItem1.amnt - 0) * checkObj1.minRate;
                    if (minRateVal > item.amnt - 0) {
                      item.amnt = ele.minAmnt || ele.maxAmnt;
                      let resValue = `${checkObj1.maxRate}倍`;
                      if (checkObj1.maxRate < 1) {
                        resValue = `${checkObj1.maxRate * 100}%`;
                      }
                      Toast(
                        `${item.productName}，最低保额不能低于 ${findItem1.productName} 保额的 ${resValue}`
                      );
                    }
                  }
                }
              }
              if (ele.premRateToOtherRisk !== undefined) {
                /*与target险种保费的投保比例值*/
                const checkObj2 = ele.premRateToOtherRisk,
                  targetArr2 = Array.isArray(checkObj2.target)
                    ? checkObj2.target
                    : [checkObj2.target],
                  findItem1 = arr.find(
                    (insu) =>
                      targetArr2.includes(insu.varietyCode) &&
                      (insu.checked || insu.ismain)
                  );
                if (findItem1) {
                  const tgPrem = Number(findItem1.prem),
                    tgPayYear = Number(
                      findItem1.payendyear !== "趸交"
                        ? findItem1.payendyear
                        : "1"
                    );
                  if (checkObj2.maxRate !== undefined) {
                    const tgTotalPrem = tgPrem * tgPayYear * checkObj2.maxRate;
                    if (Number(item.amnt) > tgTotalPrem) {
                      item.amnt = ele.minAmnt || ele.maxAmnt;
                      Toast(
                        `${item.productName}，保额不能超过主险总保费的${
                          checkObj2.maxRate * 100
                        }%`
                      );
                    }
                  }
                }
              }
              if (ele.mainPremMaxLimit !== undefined) {
                const ruleObj = ele.mainPremMaxLimit;
                if (mainPrem < ruleObj.premMin && item.amnt > ruleObj.max) {
                  item.amnt = ruleObj.max;
                  Toast(
                    `主险保费未达到 ${ruleObj.premMin} 元，，附加本保险最高保额 ${ruleObj.max} 元`
                  );
                  break;
                }
              }
            } else if (ele.type == "premLimit") {
              const maxBasePrem = ele.maxPrem || 100000000;
              // 保费校验限制
              if (Number(item.prem) > maxBasePrem) {
                item.prem = maxBasePrem;
                Toast(`${item.productName}，最高保费${maxBasePrem}元`);
                break;
              }
              if (ele.minPrem && Number(item.prem) < ele.minPrem) {
                item.prem = ele.minPrem;
                Toast(`${item.productName}，最低保费${ele.minPrem}元`);
                break;
              } else if (
                ele.checkBaseMoney &&
                Number(item.prem) % ele.checkBaseMoney !== 0
              ) {
                item.prem = ele.minPrem || ele.maxPrem;
                Toast(
                  `${item.productName}，保费需为 ${ele.checkBaseMoney} 元的整数倍`
                );
                break;
              }
            } else if (ele.type == "payYearLimit") {
              // 缴费年期校验
              if (ele.sameMainPay && ele.sameMainPay.length > 0) {
                if (ele.sameMainPay.includes(mainRisk.payendyear)) {
                  if (item.payendyear != mainRisk.payendyear) {
                    Toast(ele.errTips);
                  }
                  item.payendyear = mainRisk.payendyear;
                }
              } else if (ele.mainPayend && ele.mainPayend.length > 0) {
                if (!ele.mainPayend.includes(mainRisk.payendyear)) {
                  item.errorTip = ele.errTips;
                }
              }
            } else if (ele.type == "multLimit") {
              // 投保份数校验
              // 如果被保人是成年人，则当前订单累计总保费（首年保费*交费年期）*20%计入风险保额
              // 如果是未成年人，不校验
              if (insuAge >= 18 && ele.occuLimitMult !== undefined) {
                const checkList5 = ele.occuLimitMult || [],
                  len5 = checkList5.length;
                if (len5 > 0) {
                  let totalFee1 =
                    Number(item.prem) *
                    Number(item.payendyear === "趸交" ? "1" : item.payendyear) *
                    0.2;
                  for (let i = 0; i < len5; i++) {
                    const item5 = checkList5[i];
                    if (
                      insuOccuName === item5.code &&
                      Number(totalFee1) > item5.value
                    ) {
                      item.mult = item.multMin + "";
                      Toast(
                        `被保人所选职业为特殊职业，所选保额不得大于${
                          item5.value / 10000
                        }万，请重新选择保额`
                      );
                      break;
                    }
                  }
                }
              }
            }
          }
          /* === 选择前校验险种是否可选 === */
          // else {
          if (ele.type == "premLimit") {
            if (ele.mainPremLimit !== undefined) {
              const limitObj = ele.mainPremLimit;
              if (
                limitObj.minPrem !== undefined &&
                Number(mainPrem) < limitObj.minPrem
              ) {
                item.errorTip = `主险保费最低${limitObj.minPrem}元,才可附加本险种`;
                item.canChoose = true;
                item.checked = false;
                break;
              } else if (
                limitObj.maxPrem !== undefined &&
                Number(mainPrem) > limitObj.maxPrem
              ) {
                item.errorTip = `主险保费最高${limitObj.maxPrem}元,才可附加本险种`;
                item.canChoose = true;
                item.checked = false;
                break;
              }
            }
          } else if (ele.type == "amntLimit") {
            if (item.amntRela && item.amntRela == "sameMainPrem") {
              let err3Msg = "";
              if (ele.maxAmnt && Number(item.amnt) > ele.maxAmnt) {
                err3Msg = `最高保额为${ele.maxAmnt}元`;
              } else if (ele.minAmnt && Number(item.amnt) < ele.minAmnt) {
                err3Msg = `最低保额为${ele.minAmnt}元`;
              }
              if (err3Msg) {
                item.errorTip = `${err3Msg}，且保额需等同主险保费`;
                item.canChoose = true;
                item.checked = false;
                break;
              }
            }
          }
          // 年龄校验
          else if (ele.type == "ageLimit") {
            if (ele.tbrMaxAge && appntAge > ele.tbrMaxAge) {
              item.errorTip =
                ele.errTips || `投保人最大年龄不超过：${ele.tbrMaxAge}周岁`;
              item.limitedBy = "tbr";
              item.canChoose = true;
              item.checked = false;
              break;
            } else if (ele.tbrMinAge && appntAge < ele.tbrMinAge) {
              item.errorTip =
                ele.errTips || `投保人最小年龄不低于：${ele.tbrMinAge}周岁`;
              item.limitedBy = "tbr";
              item.canChoose = true;
              item.checked = false;
              break;
            } else if (ele.maxAge && insuAge > ele.maxAge) {
              item.errorTip =
                ele.errTips || `被保险人最大年龄不超过：${ele.maxAge}周岁`;
              item.limitedBy = "bbr";
              item.canChoose = true;
              item.checked = false;
              break;
            } else if (ele.minAge && insuAge < ele.minAge) {
              item.errorTip =
                ele.errTips || `被保险人最小年龄不低于：${ele.minAge}周岁`;
              item.limitedBy = "bbr";
              item.canChoose = true;
              item.checked = false;
              break;
            } else if (
              ele.tbrAgeCheckMainPayYear &&
              ele.tbrAgeCheckMainPayYear.length > 0
            ) {
              // 豁免险:投保人年龄>>缴费期间 (爱心+利安/415008)
              const findObj6 = ele.tbrAgeCheckMainPayYear.find(
                (fnd) => appntAge >= fnd.minValue && appntAge <= fnd.maxValue
              );
              if (findObj6 && findObj6.payyear.includes(mainRisk.payendyear)) {
                item.errorTip = `投保人年龄${findObj6.minValue}-${findObj6.maxValue}岁,且主险缴费期间为${mainRisk.payendyear}年交时,不可选`;
                item.limitedBy = "tbr";
                item.canChoose = true;
                item.checked = false;
                break;
              }
            }
          } else if (ele.type == "relationLimit") {
            // 投保关系校验
            if (ele.excludeSelf !== undefined && insuRela == ele.excludeSelf) {
              item.errorTip = ele.errTips;
              item.limitedBy = "bbr";
              item.canChoose = true;
              item.checked = false;
              break;
            }
          } else if (ele.type == "socialSecurityLimit") {
            // 社保限制校验
            if (ele.value !== insuSheBao) {
              item.errorTip = ele.errTips;
              item.limitedBy = "bbr";
              item.canChoose = true;
              item.checked = false;
              break;
            }
          } else if (ele.type == "occupationLimit") {
            // 职业限制校验
            let zhiyeLevel = insuOccu,
              uname = "被保险人";
            if (ele.tagrgetUser && ele.tagrgetUser == "tbr") {
              zhiyeLevel = appntOccu;
              uname = "投保人";
            }
            if (
              ele.maxLevel !== undefined &&
              Number(zhiyeLevel) >= Number(ele.maxLevel)
            ) {
              item.errorTip =
                ele.errTips ||
                `${uname}${ele.maxLevel}级（含）以上职业不得投保本险`;
              item.limitedBy = "bbr";
              item.canChoose = true;
              item.checked = false;
              break;
            } else if (ele.disLevelArr) {
              if (ele.disLevelArr.includes(zhiyeLevel)) {
                item.errorTip =
                  ele.errTips || `${uname}${zhiyeLevel}级职业不得投保`;
                item.limitedBy = "bbr";
                item.canChoose = true;
                item.checked = false;
                break;
              }
            } else if (
              ele.levelCheckAmnt !== undefined &&
              ele.levelCheckAmnt.length > 0
            ) {
              const checkList2 = ele.levelCheckAmnt,
                len2 = checkList2.length;
              let errFlag = false;
              for (let i = 0; i < len2; i++) {
                const item2 = checkList2[i];
                if (
                  Number(zhiyeLevel) == item2.level &&
                  Number(item.amnt) > item2.maxAmnt
                ) {
                  errFlag = true;
                  item.errorTip = `职业等级 ${item2.level} 级最高 ${item2.maxAmnt} 万`;
                  item.limitedBy = "bbr";
                  item.canChoose = true;
                  item.checked = false;
                  break;
                }
              }
              if (errFlag) {
                break;
              }
            }
          } else if (ele.type == "sexLimit") {
            // 性别限制校验
            if (ele.value !== insuSex) {
              item.errorTip = `该险种仅限${
                ele.value === "1" ? "女士" : "男士"
              }可投保,请确认修改`;
              item.limitedBy = "bbr";
              item.canChoose = true;
              item.checked = false;
              break;
            }
          } else if (ele.type == "riskAffectLimit") {
            // 险种之间关系限制校验
            let passFlag = true,
              errmsg = "";
            if (ele.nonTogether && ele.nonTogether.length > 0) {
              arr.forEach((insu) => {
                if (
                  ele.nonTogether.includes(insu.varietyCode) &&
                  insu.checked
                ) {
                  passFlag = false;
                  errmsg = `本附加险不能与${insu.productName}产品同时投保`;
                }
              });
              if (!passFlag) {
                item.errorTip = ele.errTips || errmsg;
                item.canChoose = true;
                item.checked = false;
              }
            } else if (ele.isTogether && ele.isTogether.length > 0) {
              arr.forEach((insu) => {
                if (
                  ele.isTogether.includes(insu.varietyCode) &&
                  !insu.checked
                ) {
                  passFlag = false;
                  errmsg = `本附加险必须与${insu.productName}产品同时投保`;
                }
              });
              if (!passFlag) {
                item.errorTip = ele.errTips || errmsg;
                item.canChoose = true;
                item.checked = false;
              }
            }
          } else if (ele.type == "payYearLimit") {
            if (ele.mainPayend && ele.mainPayend.length > 0) {
              //主险交费年期限制
              if (ele.mainPayend.includes(mainRisk.payendyear)) {
                // 符合mainPayend判断的,再投保人年龄-缴费年期限制
                if (ele.mainPayendConfig && ele.mainPayendConfig.length > 0) {
                  let tagEle = findListObj(
                    ele.mainPayendConfig,
                    mainRisk.payendyear,
                    "payYear"
                  );
                  if (tagEle && tagEle.maxage < appntAge) {
                    item.errorTip = tagEle.tips;
                    item.canChoose = true;
                    item.checked = false;
                  }
                }
              } else {
                // 不符合mainPayend判断的
                item.errorTip = ele.errTips;
                item.canChoose = true;
                item.checked = false;
                break;
              }
            } else if (
              ele.tbAgeCheckPayType &&
              ele.tbAgeCheckPayType.length > 0
            ) {
              // 生日当天算满1岁
              const findObj7 = findListObj(
                ele.tbAgeCheckPayType,
                mainRisk.payendyearType,
                "payType"
              );
              if (findObj7 && appntAge >= findObj7.maxAge) {
                item.errorTip = findObj7.errTips;
                item.canChoose = true;
                item.checked = false;
                break;
              }
            }
          } else if (ele.type == "insureAreaLimit") {
            const agentSheng = rootState.agent.provinceNo || "";
            if (ele.exclude && ele.exclude.includes(agentSheng)) {
              item.errorTip = ele.errTips || "代理人没有权限销售本险种";
              item.canChoose = true;
              item.checked = false;
              break;
            } else if (ele.include && !ele.include.includes(agentSheng)) {
              item.errorTip = ele.errTips || "代理人没有权限销售本险种";
              item.canChoose = true;
              item.checked = false;
              break;
            }
          } else if (ele.type == "getYearLimit") {
            // 领取年龄限制校验
            if (ele.sexAgeCheck) {
              const checkObj = ele.sexAgeCheck.find(
                (chk) =>
                  insuAge >= chk.ageRange[0] && insuAge <= chk.ageRange[1]
              );
              if (checkObj && checkObj.sexLimit !== insuSex) {
                item.errorTip = `被保险人${checkObj.ageRange[0]}~${
                  checkObj.ageRange[1]
                }周岁${insuSex == "1" ? "女士" : "男士"}不可投保`;
                item.limitedBy = "bbr";
                item.canChoose = true;
                item.checked = false;
                break;
              }
            }
          }
        }
      }
      return item;
    });

  return state;
};

const findListObj = (dutyList, value, key = "value") => {
  if (dutyList && dutyList.length > 0) {
    return dutyList.find((d) => d[key] == value);
  } else {
    return null;
  }
};
